package com.testingedu.jdbcDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.testingedu.model.TMenu;

public class TMenuDao extends BaseDao<TMenu> {
	
	public TMenuDao() {
		clazz = TMenu.class;
	}
	public List<TMenu> leftMenuList(Integer userId, Integer menuId) throws Exception{
		String sql = "select * from t_menu tm where tm.super_id = ? and tm.type > 1 and tm.id in (select tmir.menu_id from t_menu_in_role tmir "
			+ "where tmir.role_id in (select triu.role_id from t_role_in_user triu where "
			+ "triu.user_id = ?))";
		List<Object> values = new ArrayList<Object>();
		values.add(menuId);
		values.add(userId);
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql, values);
			return _resultSetToList(rs);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		finally {
			this.close();
		}
	}
	
	public TMenu info(int id) throws Exception{
		String sql = "select * from t_menu tp where tp.id = ?";
		List<TMenu> result = null;
		try {
			this.myJdbcSetValuesAndExecuteLoad(sql, id);
			result = _resultSetToList(rs);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		finally {
			close();
		}
		if(result != null && result.size() > 0) {
			return result.get(0);
		}
		return null;
	}
	
	public boolean hasChildren(Integer id) throws Exception {
		String sql = "select id from t_menu tp where tp.super_id = ?";
		List<Object> values = new ArrayList<Object>();
		values.add(id);
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql, values);
			if(rs.next()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			this.close();
		}
		return false;
	}
	
	public TMenu hasParents(Integer id) throws Exception{
		String sql = "select tm.id from t_menu tm where tm.id = (select tm1.super_id from t_menu tm1 where tm1.id = ?)";
		List<Object> values = new ArrayList<Object>();
		values.add(id);
		TMenu tMenu = null;
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql, values);
			if(rs.next()) {
				tMenu = new TMenu();
				tMenu.setId(rs.getInt("id"));
				return tMenu;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		finally {
			this.close();
		}
		return tMenu;
	}
	
	public List<TMenu> _resultSetToList(ResultSet rs) throws Exception{
		List<TMenu> result = new ArrayList<TMenu>();
		try {
			while(rs.next()) {
				TMenu tMenu = new TMenu();
				tMenu.setId(rs.getInt("id"));
				tMenu.setName(rs.getString("name"));
				tMenu.setUrl(rs.getString("url"));
				result.add(tMenu);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception();
		}
		return result;
	}
}
